package com.czh.dao.User;

import com.czh.dao.BaseDao;
import com.czh.pojo.User;
import com.mysql.cj.util.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao{
    private void setUser(ResultSet rs, User user) throws SQLException {
        user.setId(rs.getInt("id"));
        user.setUserCode(rs.getString("userCode"));
        user.setUserName(rs.getString("userName"));
        user.setUserPassword(rs.getString("userPassword"));
        user.setGender(rs.getInt("gender"));
        user.setBirthday(rs.getDate("birthday"));
        user.setPhone(rs.getString("phone"));
        user.setAddress(rs.getString("address"));
        user.setUserRole(rs.getInt("userRole"));
        user.setCreatedBy(rs.getInt("createdBy"));
        user.setModifyBy(rs.getInt("modifyBy"));
        user.setCreationDate(rs.getTimestamp("creationDate"));
        user.setModifyDate(rs.getTimestamp("modifyDate"));
    }//User实体类赋值
    @Override
    public User getLoginUser(Connection con, String userCode,String userPassword) throws SQLException {
        PreparedStatement pre = null;
        ResultSet rs = null;
        String[] param = {userCode,userPassword};
        String sql = "select * from smbms_user where userCode = ? and userPassword = ?";
        rs= BaseDao.getSelect(con,pre,rs,sql,param);
        User user = null;
        if(rs.next()){
            user = new User();
            setUser(rs, user);
        }
        BaseDao.closeConnect(null,pre,rs);
        return user;
    }

    @Override
    public int updatePassword(Connection con, int id, String userPassword) throws SQLException {
        PreparedStatement pre = null;
        String sql = "update smbms_user set userPassword = ? where id = ?";
        Object[] param = {userPassword,id};
        int update = 0;
        if(con!=null){
            update = BaseDao.getUpdate(con, pre, sql, param);
            BaseDao.closeConnect(null,pre,null);
        }
        return update;
    }

    @Override
    public int userCount(Connection con, String userName, int userRole) throws SQLException {
        PreparedStatement pre = null;
        ResultSet res = null;
        int userCount = 0;
        if (con!=null){
            StringBuffer sql = new StringBuffer();
            ArrayList<Object> list = new ArrayList<Object>();
            sql.append( "select count(1) as count from smbms_user a inner join smbms_role b on a.gender=b.id");
            if(userName!=null){
                sql.append(" and a.userName like ?");
                list.add("%"+userName+"%");
            }
            if(userRole!=0){
                sql.append(" and a.userRole = ?");
                list.add(userRole);
            }
            try {
                res = BaseDao.getSelect(con, pre, null, String.valueOf(sql), list.toArray());//将list转换为数组
                while (res.next()){
                    userCount = res.getInt("count");
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                BaseDao.closeConnect(null, pre,res);
            }
        }
        return userCount;
    }

    @Override
    public List<User> getUserList(Connection con, String userName, int userRole, int currentPageNo, int pageSize) throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> userList = new ArrayList<>();
        if (con != null) {
            StringBuffer sql = new StringBuffer("select u.*,r.roleName as `userRoleName` from smbms_user u,smbms_role r where u.userRole=r.id");
            List<Object> list = new ArrayList<>();
            if (!StringUtils.isNullOrEmpty(userName)) {
                sql.append(" and u.userName like ?");
                list.add("%" + userName + "%");
            }
            if (userRole > 0) {
                sql.append(" and r.id = ?");
                list.add(userRole);
            }
            sql.append(" order by u.creationDate desc limit ?,?");
            currentPageNo = (currentPageNo - 1) * pageSize;
            list.add(currentPageNo);
            list.add(pageSize);
            Object[] params = list.toArray();
            rs = BaseDao.getSelect(con, ps, rs, sql.toString(), params);
            while (rs.next()) {
                User user = new User();
                setUser(rs,user);
                user.setUserRoleName(rs.getString("userRoleName"));
                userList.add(user);
            }
            BaseDao.closeConnect(null, ps, rs);
        }
            return userList;
    }

    @Override
    public int userAdd(Connection connection, User user) throws Exception {
        PreparedStatement pre = null;
        int i = 0;
        if(connection != null){
            String sql = "insert into smbms_user (userCode,userName,userPassword," +
                    "userRole,gender,birthday,phone,address,creationDate,createdBy) " +
                    "values(?,?,?,?,?,?,?,?,?,?)";
            Object[] params = {user.getUserCode(), user.getUserName(), user.getUserPassword(),
                    user.getUserRole(), user.getGender(), user.getBirthday(),
                    user.getPhone(), user.getAddress(), user.getCreationDate(), user.getCreatedBy()};
            i = BaseDao.getUpdate(connection, pre, sql, params);
        }
        BaseDao.closeConnect(null,pre,null);
        return i;
    }
//    @Test
//public void Text() throws Exception {
//    Connection connection = BaseDao.getConnection();
//    User user = new User();
//    user.setUserCode("007");
//    user.setUserName("测试");
//    user.setUserPassword("123456");
//    user.setGender(1);
//    user.setBirthday(new Date());
//    user.setPhone("15908754730");
//    user.setAddress("测试地址");
//    user.setUserRole(3);
//    user.setCreatedBy(3);
//    user.setModifyBy(3);
//    int i = new UserDaoImpl().userAdd(connection, user);
//    System.out.println(i);
//}
    @Override
    public User userCodeSeek(Connection connection, String userCode) {
        PreparedStatement pre = null;
        String sql = "select * from smbms_user where userCode = ?";
        ResultSet res = null;
        Object [] params = {userCode};
        User user = null;
        try {
            res = BaseDao.getSelect(connection, pre, res, sql, params);
            while (res.next()){
                user = new User();
                setUser(res,user);
            }
            BaseDao.closeConnect(null,pre,res);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user;
    }

    @Override
    public User userIdSeek(Connection connection, Integer id) {
        PreparedStatement pre = null;
        ResultSet res = null;
        String sql = "select a.*,b.roleName from smbms_user a,smbms_role  b where a.userRole = b.id and a.id = ?";
        User user = new User();
        try {
            Object [] params = {id};
            res = BaseDao.getSelect(connection, pre, res, sql, params);
            while (res.next()) {
                setUser(res, user);
                user.setUserRoleName(res.getString("roleName"));
            }
            BaseDao.closeConnect(null,pre,res);
        }catch (Exception e){
            throw new RuntimeException("Dao层userIdSeek系统错误!");
        }
        return user;
    }

    @Override
    public int userDelete_id(Connection connection, Integer id) {
        PreparedStatement pre = null;
        String sql = "delete from smbms_user where id=?";
        Object[] params = {id};
        int delete;
        try {
            delete = BaseDao.getUpdate(connection, pre, sql, params);
            BaseDao.closeConnect(null,pre,null);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return delete;
    }

    @Override
    public int modify(Connection connection, User user) {
        PreparedStatement pre = null;
        int modify;
        String sql = "update smbms_user set userName = ?,gender=?," +
                "birthday=?,phone=?,address=?,userRole=? where id = ?";
        Object [] params = {user.getUserName(),user.getGender(),user.getBirthday(),user.getPhone(),
        user.getAddress(),user.getUserRole(),user.getId()};
        try {
            modify = BaseDao.getUpdate(connection, pre, sql, params);
            BaseDao.closeConnect(null,pre,null);
        }catch (Exception e){
            throw new RuntimeException("Bao层modify出错");
        }
        return modify;
    }
}
